<?php
	class VoteAction extends BaseAction{
		//投票
		public function vote(){
			if(empty($_POST['vote'])){
				$this->error('请选择投票选项！','__APP__');
				exit();
			}
			//验证ip和cookie时间防止刷票
			if(cookie('ip') == $_SERVER['REMOTE_ADDR'] && time() - cookie('time') < 86400){
				$this->error('您今天已经投过票了！请不要重复投票！','__URL__/show');
				exit();
			}
			$vote = M('VoteItem');
			if($vote->where('id = '.$_POST['vote'])->setInc('count',1)){
				//用cookie记录客户端ip和时间，防止刷票
				cookie('ip',$_SERVER["REMOTE_ADDR"],86400);
				cookie('time',time(),86400);
				$this->success('恭喜！投票成功！','__APP__/Vote/show');
			}else{
				$this->error('投票失败！','__APP__');
			}
		}
		
		//显示投票结果页面
		public function show(){
			$voteSub = M('VoteSubject');
			$voteSubData = $voteSub->field('zgcms_vote_subject.id,zgcms_vote_subject.title,sum(count) count')
								->join('zgcms_vote_item on zgcms_vote_subject.id = zgcms_vote_item.sid')
								->where('state = 1')
								->group('zgcms_vote_subject.id')
								->find();
			$voteItem = M('VoteItem');
			$voteItemData = $voteItem->field('id,title,count')
									->where('sid = '.$voteSubData['id'])
									->select();
			$width = 400;
			for($i = 0; $i < count($voteItemData); $i++){
				$voteItemData[$i]['percent'] = round($voteItemData[$i]['count'] / $voteSubData['count'] * 100, 2).'%';
				$voteItemData[$i]['width'] = $voteItemData[$i]['count'] / $voteSubData['count'] * $width;
				$voteItemData[$i]['picnum'] = rand(1,4);
			}
			$this->assign('voteSub',$voteSubData);
			$this->assign('width',$width);
			$this->assign('voteItem',$voteItemData);
			$this->display();
		}
	}

?>